package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.entity.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper,ApUser> implements ApUserService{
    /**
     * App端登录
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult  login(LoginDto loginDto) {
        //1:正常用户登录
        if(StringUtils.hasText(loginDto.getPhone()) && StringUtils.hasText(loginDto.getPassword())){
            //根据手机号查询用户信息
            ApUser apUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()));
            if (apUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"用户不存在");
            }
            //用户登录传入的密码
            String password = loginDto.getPassword();
            //数据库中的盐值
            String salt = apUser.getSalt();
            //把用户传入的明文密码加上数据库中的盐值，一起加密之后，得到加密之后的密码
            String pwd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if(!pwd.equals(apUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //返回jwt令牌
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            map.put("user",apUser);
            //把数据库中盐值和password都重置为空，不要返回给前端
            apUser.setSalt("");
            apUser.setPassword("");
            return ResponseResult.okResult(map);
        }else {
            //游客登录
            Map<String,Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }
}
